<?php

namespace App\WsController;

use App\Model\User\UserModel;
use App\Msg\MsgCode;
use App\Msg\MsgInfo;
use App\Server\Task\UserOnlineTask;
use EasySwoole\Core\Http\Message\Status;
use EasySwoole\Core\Swoole\Task\TaskManager;
use EasySwoole\Core\Swoole\Time\Timer;
use EasySwoole\Core\Component\Logger;
use EasySwoole\Core\Swoole\ServerManager;

class User extends WsAbstract {
	function getUserInfo() {
		$user = (new UserModel ())->getUserByToken ( $this->token );
		$user->setPassword ( "" );
		$this->writeJson ( Status::CODE_OK, $user->toArray (), MsgInfo::User ( MsgCode::GET_USER_SUCCESS ) );
	}
	function openChat() {
		$fd = $this->client ()->getFd ();
		(new UserModel ())->updateUserbyToken ( $this->token, "fd", $fd );
		$user = (new UserModel ())->getUserByToken ( $this->token );
		(new UserModel ())->addFdAndToken ( $fd, $this->token );
		$flag = (new UserModel ())->addUidAndFd ( $user->getUid (), $fd );
		if ($flag) {
			(new UserModel ())->onLineNumUp ();
			TaskManager::async ( (new UserOnlineTask ( [ 
					"userinfo" => $user->toArray () 
			] )) );
			$this->writeJson ( Status::CODE_OK, [ 
					'myfd' => $fd 
			], MsgInfo::User ( MsgCode::CHAT_OPEN_SUCCESS ) );
		}
	}
	function timePush() {
		$fd = $this->client ()->getFd ();
		$server = ServerManager::getInstance ()->getServer ();
		Timer::loop ( 1000, function () use ($fd, $server) {
			Logger::getInstance ()->console ( $fd );
			$server->push ( $fd, json_encode ( [ 
					'轮询推送' 
			] ) );
		} );
		TaskManager::async ( function () use ($fd) {
			ServerManager::getInstance ()->getServer ()->push ( $fd, json_encode ( [ 
					'异步推送' 
			] ) );
		} );
	}
}